package com.xms.security.verification.api.controller;

import com.xms.core.annotation.AllowAnonymous;
import com.xms.security.verification.core.IVerifyProvider;
import com.xms.security.verification.model.VerifyValue;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>
 * RandomImageController
 * </p>
 *
 * @author migo
 * @since 2021/11/6
 */
@AllowAnonymous
@Api("图片验证码接口")
@RestController
@RequestMapping({"/api/verify/randomimage"})
public class RandomImageController {
    private IVerifyProvider _verifyProvider;

    @Autowired
    public void RandomImageController(IVerifyProvider verifyProvider) {
        _verifyProvider = verifyProvider;
    }

    @ApiOperation(value = "获取验证码")
    @GetMapping("/get")
    public void get(HttpServletRequest request, HttpServletResponse response) {
        try {
            VerifyValue verifyCode = _verifyProvider.get();
            String code = verifyCode.code;
            response.addHeader("encodevalue", code);
            //设置响应头，不允许缓存
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setContentType(verifyCode.mediaType);
            response.getOutputStream().write(verifyCode.value);
            response.getOutputStream().flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
